//
//  ScannerLoginViewController.m
//  NongWanCloud
//
//  Created by YueWen on 2018/3/20.
//  Copyright © 2018年 YueWen. All rights reserved.
//

#import "QDScannerTicketViewController.h"
#import "HBDNavigationController.h"
#import "QDMetroClient-Swift.h"


@interface QDScannerTicketViewController ()<RITLScannerDelegate>

/// 完成后的回调
@property (nonatomic, copy) dispatch_block_t completehandler;
/// 描述的标签
@property (nonatomic, strong) UILabel * descLabel;

@end

@implementation QDScannerTicketViewController

//
//+ (void)presentScannerLoginViewControllerFromController:(UIViewController *)viewController
//{
//    [self presentScannerLoginViewControllerFromController:viewController projectId:@""];
//}
//
//
//+ (void)presentScannerLoginViewControllerFromController:(UIViewController *)viewController orderId:(NSString *)orderId complete:(dispatch_block_t)completeHander {
//
//}
//


+ (void)presentScannerLoginViewControllerFromController:(UIViewController *)viewController orderId:(NSString *)orderId complete:(dispatch_block_t)completeHander
{
    if (!viewController) { return; }
    
    [viewController presentViewController:[[HBDNavigationController alloc]initWithRootViewController:({
        
        QDScannerTicketViewController *loginController = QDScannerTicketViewController.new;
        loginController.orderId = orderId;
        loginController.completehandler = completeHander;
        loginController;
        
    })] animated:true completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"扫一扫";
    
    //设置导航返回
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:self.backIndicatorImage.ritl_image.ritl_renderOriginImage style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
//    self.navigationItem.leftBarButtonItem.imageInsets = UIEdgeInsetsMake(-1.5, -9, 0, 0);
    
    //追加扫描框
    [self.view addSubview:self.scannerView];
    [self.view addSubview:self.descLabel];
    
    CGFloat width = self.ritl_width - 2 * 52;
    CGFloat topSpace = ((self.ritl_height - RITL_DefaultNaviBarHeight) - width) / 2;
    topSpace = topSpace + RITL_DefaultNaviBarHeight - 40 + width + 10;
    
    //布局
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.offset(topSpace);
        make.left.offset(42);
        make.right.inset(42);
    }];
    
    [self.scannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.scannerView.indicatorView startAnimating];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.scannerView start];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.scannerView stop];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dismiss
{
    [self.scannerView stop];
    [self dismissViewControllerAnimated:true completion:nil];
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


- (UIColor *)nav_titleColor {
    return UIColor.whiteColor;
}

- (float)nav_barAlpha {
    return 0.0;
}


#pragma mark - getter

- (RITLScannerView *)scannerView
{
    if (!_scannerView) {
        
        CGFloat width = self.ritl_width - 2 * 52;
        CGFloat topSpace = ((self.ritl_height - RITL_DefaultNaviBarHeight) - width) / 2;
        _scannerView = [RITLScannerView new];
        _scannerView.delegate = self;
        _scannerView.scannerInset = UIEdgeInsetsMake(topSpace + RITL_DefaultNaviBarHeight - 40, 52, 0, 52);
    }
    
    return _scannerView;
}


- (UILabel *)descLabel
{
    if (!_descLabel) {
     
        _descLabel = [UILabel new];
        _descLabel.numberOfLines = 3;
        _descLabel.textColor = UIColor.whiteColor;
        _descLabel.font = RITLRegularFont(15);
        _descLabel.textAlignment = NSTextAlignmentCenter;
        _descLabel.text = @"将二维码放入框内,即可自动扫描";
    }
    
    return _descLabel;
}



#pragma mark - ScannerDelegate

- (void)scannerView:(RITLScannerView *)scannerView data:(AVMetadataObject *)object
{
    if ([object.type isEqualToString:AVMetadataObjectTypeQRCode] ) {
        
         [self.scannerView stop];
        NSLog(@"qrcode = %@",[(AVMetadataMachineReadableCodeObject *)object stringValue]);
        
        [self handleQrCodeString:[(AVMetadataMachineReadableCodeObject *)object stringValue]];

    }
}


- (void)handleQrCodeString:(NSString *)qrcode {
    
    /// 进行base64解码
    NSData *data = [[NSData alloc]initWithBase64EncodedString:qrcode options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    //进行数组拆
    NSArray <NSString *>*resultArray = [result componentsSeparatedByString:@"|"];
    
    // 表示是车票
    if(resultArray.count == 3) {
        //进行请求取车票
        [self requestTicketByScanner:resultArray];
    }
    else {
        ShowMBHUD(@"无法识别二维码信息", self.view);
        [self.scannerView start];
    }
}


/// 请求取票
- (void)requestTicketByScanner:(NSArray <NSString *> *)code {
    
    __weak typeof(self) weakSelf = self;
    
    [self requestFetchTicketsWithMessage:code complete:^{
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        ShowMBHudwithDelayTime(@"请求取票成功,请取票", strongSelf.view, 1.5);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            /// 执行回调
            strongSelf.completehandler();
            [strongSelf.navigationController dismissViewControllerAnimated:true completion:nil];
        });
        
    }];
}


@end
